const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080, host: '0.0.0.0' });

// 存储在线客户端：{ clientId: WebSocket }
const clients = new Map();

wss.on('connection', (ws) => {
    let clientId = null;

    // 接收客户端消息
    ws.on('message', (data) => {
        const message = JSON.parse(data.toString());
        
        switch (message.type) {
            // 客户端注册ID
            case 'register':
                clientId = message.id;
                clients.set(clientId, ws);
                ws.send(JSON.stringify({ type: 'register-success' }));
                console.log(`客户端 ${clientId} 已注册`);
                break;

            // 转发offer/answer/candidate到目标客户端
            case 'offer':
            case 'answer':
            case 'candidate':
                const targetWs = clients.get(message.to);
                if (targetWs) {
                    targetWs.send(JSON.stringify({
                        ...message,
                        from: clientId // 补充发送方ID
                    }));
                    console.log(`转发 ${message.type} 从 ${clientId} 到 ${message.to}`);
                } else {
                    ws.send(JSON.stringify({
                        type: 'error',
                        error: '目标客户端未在线'
                    }));
                }
                break;

            default:
                ws.send(JSON.stringify({
                    type: 'error',
                    error: '未知消息类型'
                }));
        }
    });

    // 客户端断开连接
    ws.on('close', () => {
        if (clientId) {
            clients.delete(clientId);
            console.log(`客户端 ${clientId} 已断开`);
        }
    });
});

console.log('信令服务器运行中，端口：8080');
    